package jp.co.ledinge.syllabarygame;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ProblemActivity extends Activity {

	private ImageView lifeView1;
	private ImageView lifeView2;
	private BoxView characterView1;
	private BoxView characterView2;
	private BoxView characterView3;
	private BoxView characterView4;
	private List<BoxView> mCharacterImages;
	private List<LinearLayout> mCharacterLayouts;
	private ArrayList<Question> mQuestions;
	private ImageView mQuestionImage;
	private int mQuestionNo = 0;
	private TextView mNumQuestionText;
	private SoundPool mSoundPool;
	private Question mCurrentQuestion;
	private TextView mResultText;
	private boolean mResult = false;
	/** 文字認識エンジン */
	private Recognize mRecognize;

	private static final String TAG = "SyllabaryGame";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.problem);
		lifeView1 = (ImageView) findViewById(R.id.lifeView1);
		lifeView2 = (ImageView) findViewById(R.id.lifeView2);
		mResultText = (TextView) findViewById(R.id.result);
		mNumQuestionText = (TextView) findViewById(R.id.num_question);
		characterView1 = (BoxView) findViewById(R.id.characterView1);
		characterView2 = (BoxView) findViewById(R.id.characterView2);
		characterView3 = (BoxView) findViewById(R.id.characterView3);
		characterView4 = (BoxView) findViewById(R.id.characterView4);
		mCharacterImages = new ArrayList<BoxView>();
		mCharacterImages.add(characterView1);
		mCharacterImages.add(characterView2);
		mCharacterImages.add(characterView3);
		mCharacterImages.add(characterView4);
		mCharacterLayouts = new ArrayList<LinearLayout>();
		LinearLayout characterLayout = (LinearLayout) findViewById(R.id.characterLayout1);
		mCharacterLayouts.add(characterLayout);
		characterLayout = (LinearLayout) findViewById(R.id.characterLayout2);
		mCharacterLayouts.add(characterLayout);
		characterLayout = (LinearLayout) findViewById(R.id.characterLayout3);
		mCharacterLayouts.add(characterLayout);
		characterLayout = (LinearLayout) findViewById(R.id.characterLayout4);
		mCharacterLayouts.add(characterLayout);
		mQuestionImage = (ImageView) findViewById(R.id.question_image);
		mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
		loadApps();
		question();

		try {
			InputStream input;
			AssetManager as = getResources().getAssets();
			input = as.open("SaveData.dat");
			ObjectInputStream ois = new ObjectInputStream(input);
			HashMap<String, Pattern> readObject = (HashMap<String, Pattern>) ois
					.readObject();
			mRecognize = new Recognize(readObject, this.getResources().getStringArray(R.array.char_list));
			ois.close();
			input.close();
		} catch (Exception e) {
			Log.e(TAG, "Error", e);
		}

	}

	/**
	 * 全BoxViewを消します
	 * 
	 * @param view
	 */
	public void onClickCls(View view) {
		for (BoxView boxView : mCharacterImages) {
			boxView.clearDrawList();
		}
	}
	/**
	 * 結果が表示されていて、それが押下された場合の処理。
	 * 結果を消して、正解なら次の問題へ進む。
	 * 不正解ならそのまま。
	 * @param view
	 */
	public void onClickNext(View view) {
		mResultText.setVisibility(View.GONE);
		if (mResult) {
			mQuestionNo++;
			if (mQuestions.size() <= mQuestionNo) {
				mQuestionNo = 0;
			}
			question();
		}
	}

	private void initCharacterView() {
		for (LinearLayout characterLayout : mCharacterLayouts) {
			characterLayout.setVisibility(View.GONE);
		}
		for (BoxView boxView: mCharacterImages) {
			boxView.clearDrawList();
		}
	}
	/**
	 * 問題を出す。mQuestionNoを元に出題をする。
	 */
	private void question() {
		initCharacterView();
		mCurrentQuestion = mQuestions.get(mQuestionNo);
		for (int i = 0; i < mCurrentQuestion.mLength; i++) {
			LinearLayout characterLayout = mCharacterLayouts.get(i);
			characterLayout.setVisibility(View.VISIBLE);
		}
		mQuestionImage.setImageResource(mCurrentQuestion.mImageId);
		int no = mQuestionNo + 1;
		mNumQuestionText.setText(String.valueOf(no));
		mSoundPool.play(mCurrentQuestion.mSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
	}

	private void loadApps() {
		String[] answer = getResources().getStringArray(
				R.array.raw_string_answer);
		TypedArray array = getResources().obtainTypedArray(
				R.array.raw_ids_sound);
		TypedArray imageArray = getResources().obtainTypedArray(
				R.array.raw_ids_image);
		mQuestions = new ArrayList<Question>(array.length());
		for (int i = 0; i < answer.length; i++) {
			Question question = new Question();
			int soundId = array.getResourceId(i, 0);
			if (soundId == 0) {
				continue;
			}
			question.mSoundId = mSoundPool.load(this.getApplicationContext(),
					soundId, 0);
			question.mImageId = imageArray.getResourceId(i, 0);
			question.mAnswer = answer[i];
			question.mLength = answer[i].length();
			mQuestions.add(question);
		}
		array.recycle();
		imageArray.recycle();
		Random rnd = new Random(System.currentTimeMillis());
		Collections.shuffle(mQuestions, rnd);
	}

	/**
	 * SoundPoolの解放。
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mSoundPool.release();
	}

	public void onClickPlaySound(View view) {
		mSoundPool.play(mCurrentQuestion.mSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
	}
	/**
	 * 決定ボタン押下時の処理
	 * @param view
	 */
	public void onClickOk(View view) {
		// けってい
		mResult = true;
		for (int i = 0; i < mCurrentQuestion.mLength; i++) {
			BoxView boxView = mCharacterImages.get(i);
			char answer = mCurrentQuestion.mAnswer.charAt(i);
			// 比較
			if (!recognize(boxView, answer)) {
				boxView.clearDrawList();
				mResult = false;
			}
		}
		this.getResources().getString(R.string.success);
		mResultText.setVisibility(View.VISIBLE);
		if (mResult) {
			// 正解
			mResultText.setText(this.getResources().getString(R.string.success));
		} else {
			// 不正解
			mResultText.setText(this.getResources().getString(R.string.fail));
		}
		mSoundPool.play(mCurrentQuestion.mSoundId, 1.0f, 1.0f, 0, 0, 1.0f);
	}

	private boolean recognize(BoxView boxView, char input) {
		ArrayList<Pattern> patternList = mRecognize.recognize(boxView);
		if (patternList.size() < 3) {
			return false;
		}
		for (int i = 0; i < 3; i++) {
			char[] a = patternList.get(i).getCharStr().toCharArray();
			Log.v(TAG, "Input = " + a[0]);
			if (input == a[0]) {
				return true;
			}
		}
		return false;
	}

}
